import React, { useCallback, useEffect, useState } from 'react'

// antd
import {
  Timeline,
  Card,
  Form,
  Input,
  Select,
  Button,
  InputNumber,
  Space,
} from 'antd';

// axios
import { getStocksTipsData } from '../../api/stock';

// redux
import { resetTipsNum, setTipsNum } from '../../actions/stock';
import { connect } from 'react-redux';

function InventoryNews(props) {
  // 注册表单
  const [thresholdForm] = Form.useForm()

  // 获取基本阈值
  const [defaultThreshold, setThreshold] = useState(props.threshold)

  // 设置阈值
  const onFinish = useCallback((values) => {
    // 调用方法
    props.set(values.num)
    // 重新获取数据
    getTipsData(values.num)
  }, [])

  // 重置按钮 默认为10
  const onReset = useCallback(() => {
    // 调用重置
    props.reset()
    // 更替页面显示
    thresholdForm.setFieldsValue({
      num: 10,
    })
    // 重新获取数据
    getTipsData(10)
  }, [])

  // 事件轴提醒数据
  const [stockTipsData, setTipData] = useState([])

  // 挂载后查询数据
  useEffect(() => {
    getTipsData()
  }, [])

  const getTipsData = useCallback(async(threshold = defaultThreshold) => {
    const data = await getStocksTipsData(threshold)
    setTipData(data)
  }, [])

  return (
    <div>
      <Form
        name="customized_form_controls"
        layout="inline"
        onFinish={onFinish}
        form={thresholdForm}
        initialValues={{
          num: defaultThreshold,
        }}
        style={{
          marginBottom: '20px',
        }}
      >
        <Form.Item
          name="num"
          label="设置库存余额提醒阈值"
          rules={[{ required: true }]}
        >
          <InputNumber min={1} addonAfter="件" />
        </Form.Item>
        <Form.Item>
          <Space>
            <Button type="primary" htmlType="submit">
              设置
            </Button>
            <Button type="primary" onClick={onReset}>
              重置
            </Button>
          </Space>
        </Form.Item>
      </Form>
      <Timeline color="#40A9FF" >
        {
          stockTipsData.length === 0
            ? <div>暂无商品库存不足阈值</div>
            : stockTipsData.map((value) => (
              <Timeline.Item key={value.id}>
                <Card title={value.name} extra={<a href={'#/inventory/inventoryPost?id=' + value.id}>立即进货</a>} style={{ width: 300 }}>
                  <p>库存小于等于阈值，仅余{value.amount}件！！！</p>
                </Card>
              </Timeline.Item>
            ))

        }
      </Timeline>
    </div>
  )
}


// connect 导入
const mapStateToProps = (state) => ({
  threshold: state.stock.stockTipsThreshold,
})

const mapDispatchToProps = (dispatch) => ({
  set: (num) => dispatch(setTipsNum(num)),
  reset: () => dispatch(resetTipsNum()),
})

export default connect(mapStateToProps, mapDispatchToProps)(InventoryNews)
